package com.cqemme.activitiservice.listener;


import com.alibaba.fastjson.JSONObject;
import com.cqemme.activitiservice.feign.UserServiceFeign;
import com.cqemme.activitiservice.service.ListenerService;
import com.cqemme.comm.po.Result;
import com.cqemme.comm.utils.JackSonUtils;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import lombok.extern.slf4j.Slf4j;
import org.activiti.bpmn.model.FlowElement;
import org.activiti.bpmn.model.UserTask;
import org.activiti.engine.delegate.DelegateExecution;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 公共报警监听
 *
 * @author nejery
 */
@Service("commonAlarmListener")
@Slf4j
public class CommonAlarmListener {

    @Resource
    private ListenerService listenerService;


    @Resource
    private UserServiceFeign userServiceFeign;


    /**
     * 推送消息给相关人员
     * @param execution 执行对象
     */
    public void sendMessage(DelegateExecution execution) {
        log.info("流程实例id:{}", execution.getProcessInstanceId());
        Object isSendMessageToSave = execution.getVariable("isSendMessageToSave");
        if(null == isSendMessageToSave){
            listenerService.sendToSchoolSave(execution);
            listenerService.setVariable(execution,"isSendMessageToSave","1");
            try {
                Thread.sleep(2000);
                listenerService.sendNodeMessage(execution);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }else{
            listenerService.sendNodeMessage(execution);
        }
    }


    /**
     * 设置前端类型
     */
    public void setFontVariable(DelegateExecution execution) {
        Map map =  listenerService.getCurrentNodeBpmnVariables(execution);
        String nodeKey = execution.getCurrentActivityId() + "_extendFields";
        listenerService.setVariable(execution,nodeKey,JackSonUtils.beanToString(map));
    }

    /**
     * 重复发送推送消息
     * @param execution  执行对象
     */
    public void repeatSendMessage(DelegateExecution execution){
        //execution.getVariable();
        listenerService.repeatSendMessage(execution);
        log.info("重复执行！！！");
    }

    /**
     * 查找领导
     * @param execution 执行对象
     */
    public void leaderHandle(DelegateExecution execution) {

        //学校id
        String schoolId = execution.getVariable("orgCode").toString();
        log.info("领导处理： 学校id：{}",schoolId);
        //得到参数和值数组
        String roles =  listenerService.getLastNodeValue(execution, "_roles");
        if(null != roles){
            //学校人员分配
            Map<String, Object> map = new HashMap<>();
            map.put("orgId", Integer.parseInt(schoolId));
            map.put("roleList", new ArrayList<>(Arrays.asList(roles.split(","))));
            Result rolesResult = userServiceFeign.getRolesUser(map);
            ArrayNode resultSuccessDataArrayNode = JackSonUtils.getResultSuccessDataArrayNode(JackSonUtils.beanToString(rolesResult));
            log.info("角色{}对应人员：{}",roles,JackSonUtils.beanToString(rolesResult) );
            if(null != resultSuccessDataArrayNode){
                List<String> roleList = new ArrayList<>();
                for (JsonNode jsonNode : resultSuccessDataArrayNode){
                    roleList.add(jsonNode.asText());
                    FlowElement currentFlowElement = execution.getCurrentFlowElement();
                    UserTask userTask = (UserTask) currentFlowElement;
                    userTask.setCandidateUsers(roleList);
                }
            }else{
                log.error("但查无对应组织的队长(如保安队长)，此流程实例被挂起。参数：{}，返回值：{}，流程实例id：{}", JSONObject.toJSONString(map), JSONObject.toJSONString(rolesResult), execution.getProcessInstanceId());
            }
        }else{
            log.error("未找到分配角色。");
        }


    }
}
